package microservice

import (
	"hxy/repo/database"
	"hxy/repo/model"
	"os"
	"path"

	"gorm.io/gorm"
)

var mdb *gorm.DB

func init() {
	mdb = database.GetConnect()
	mdb.AutoMigrate(&SubModule{})
}

type SubModule struct {
	Id           uint         `json:"id" gorm:"AUTO_INCREMENT"`
	ProjectId    uint         `json:"project_id"`
	Name         string       `json:"name"`
	LanguageType LanguageType `json:"languagetype"`
	Dockerfile   bool         `json:"dockerfile"`
}

var TestautoIdentifySubProject = autoIdentifySubProject
var ignore_dir = []string{".git", ".github", "script", "doc", "old-docs"}

// / 自动解析路径并保存至数据库
func autoIdentifySubProject(git model.GitModel) error {
	mdb.Where("project_id = ?", git.ID).Delete(&SubModule{})
	sub_dir, err := os.ReadDir(git.Path)
	if err != nil {
		return err
	}
	for _, module := range sub_dir {
		_name := module.Name()
		if !module.IsDir() {
			continue
		}
		for _, str := range ignore_dir {
			if str == _name {
				continue
			}
		}
		havedocker, lt := checkSubModule(path.Join(git.Path, _name))
		submodel := SubModule{
			ProjectId:    git.ID,
			Name:         _name,
			LanguageType: lt,
			Dockerfile:   havedocker,
		}
		mdb.Create(&submodel)
	}
	return nil
}

// The sub Module's Dir which contain the Dockerfile
func ready2dockerbuildModule(gitid uint) []SubModule {
	gitm, _ := database.GitById(int(gitid))
	autoIdentifySubProject(gitm)
	var list []SubModule
	mdb.Where("project_id = ? AND dockerfile = 1", gitid).Find(&list)
	return list
}

// 已经存在Dockerfile 的子模块
func DockerBuildPathofSubModule(git model.GitModel) []string {

	modules := ready2dockerbuildModule(git.ID)
	var list []string
	for _, sub := range modules {
		list = append(list, sub.Name)
	}
	return list
}
